package com.pjh.shitang.advices;

import com.alibaba.fastjson.JSON;
import com.pjh.shitang.utils.vo.returns.ResponseBody;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author yueyinghaibao
 * @date 2022/5/1
 */
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(body instanceof Boolean) {
            return (Boolean) body ? ResponseBody.success() : ResponseBody.error("谜之错误");
        }
        if(body instanceof String) {
            return JSON.toJSON(ResponseBody.success(body));
        }
        if(body instanceof ResponseBody) {
            return body;
        }
        return ResponseBody.success(body);
    }
}
